package com.gopay.webtest.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

public class ReflectUtil {

    static List<String> list = new ArrayList<>();
    
    private static Logger logger = Logger.getLogger(ReflectUtil.class);
    
    static{
        list.add("buyerRealMobile");
        list.add("buyerRealBankAcctNum");
        list.add("buyerRealCertNo");
        list.add("buyerRealName");
        list.add("creditCardExpired");
        list.add("cvn2");
        list.add("smsAuthCode");
    }
    
    /**
     * des 加密关键字段
     * @param obj
     * @throws Exception 
     * @throws  
     */
    public static void desField(Object obj, String key) throws  Exception {
        Encrypt des = new  Encrypt(key);
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            String value = (String) field.get(obj);
            if (value != null && !"".equals(value)) {
                if (list.contains(name)) {
                    logger.info("name= " + name + ", 原文=" + value);
                    value = des.encrypt(value);
                    logger.info("name= " + name + ", 密文=" + value );
                    
                    //设置值
                    setFieldValue(obj, name, value);
                }
            }
        }
    }
    
    
    /**
     * 类转换成map
     * @param obj
     * @param map
     * @throws Exception
     */
    public static void copyFiledToMap(Object obj, Map<String, String> map) throws Exception {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String value = (String) field.get(obj);
            map.put(field.getName(), value);
        }
    }
    
    
	public static String getFieldValue(Object obj, String fieldNAme)
			throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {

		Field[] fields = obj.getClass().getDeclaredFields();
		String value = null;
		for (Field field : fields) {
			if(fieldNAme.equals(field.getName())){
				field.setAccessible(true);
				value = (String) field.get(obj);
				break;
			}
			
		}
		return value;
	}

	public static void setFieldValue(Object obj, String fieldNAme, Object Value)
			throws IllegalArgumentException, IllegalAccessException {

		Field[] fields = obj.getClass().getDeclaredFields();
		
		String value = null;
		for (Field field : fields) {
			if(fieldNAme.equals(field.getName())){
				field.setAccessible(true);
				field.set(obj, Value);
				break;
			}
		}

	}
	
}
